"""
@Author    : ghenyar
@Time      : 2025/8/28 11:13
@File      : config
@Desc      : 配置
"""
import os
import urllib.parse
from typing import Any

from sqlalchemy import AsyncAdaptedQueuePool
from sqlalchemy.pool import QueuePool
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()


class Config:
    def __init__(self):
        self.redis = self._get_redis_config()
        self.jwt = self._get_jwt_config()
        self.database = self._get_database_config()

    def _get_redis_config(self):
        """
        redis配置
        :return:
        """

        class RedisConfig:
            def __init__(self):
                self.host: str = os.getenv("REDIS_HOST", "127.0.0.1")  # Redis 服务器的主机地址
                self.port: int = os.getenv("REDIS_PORT", 6379)  # Redis 服务器的端口号
                self.db: int = os.getenv("REDIS_DB",
                                         0)  # 使用的 Redis 数据库索引  Redis 默认有 16 个数据库（索引从 0 到 15），这里使用的是第 0 个数据库。
                self.password: str = os.getenv("REDIS_PASSWORD", "")  # Redis 服务器的密码（如果没有设置密码，则为空字符串）
                self.prefix = os.getenv("REDIS_PREFIX", "")  # 键的前缀（如果需要为所有键添加前缀，可以在这里设置）

        return RedisConfig()

    def _get_jwt_config(self):
        """
        jwt配置
        :return:
        """

        class JwtConfig:
            def __init__(self):
                self.secret: str = os.getenv("JWT_SECRET",
                                             "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7")
                self.algorithm: str = os.getenv("JWT_ALGORITHM", "HS256")
                self.expires: int = os.getenv("JWT_EXPIRATION", 600)  # m(分钟) jwt默认过期时间为60分钟

        return JwtConfig()

    def _get_database_config(self):
        """
        获取数据库配置
        :return:
        """

        class DatabaseConfig:
            def __init__(self):
                self.dialect: str = os.getenv("DB_DIALECT", "mysql")
                self.host: str = os.getenv("DB_HOST", "localhost")
                self.port: int = os.getenv("DB_PORT", 3306)
                self.user: str = os.getenv("DB_USER", "root")
                self.password: str = os.getenv("DB_PASSWORD", "")
                self.db_name: str = os.getenv("DB_DATABASE", "")
                self.prefix: str = os.getenv("DB_PREFIX", "")
                self.debug: bool =False
                self.charset: str = os.getenv("DB_CHARSET", "utf8mb4")
                self.use_tz: bool = True  # 是否使用时区
                self.timezone: str = "+08:00"  # 时区设置

                # 连接池配置
                self.pool_size: int = int(os.getenv("DB_POOL_SIZE", 5))
                self.max_overflow: int = int(os.getenv("DB_MAX_OVERFLOW", 10))
                self.pool_recycle: int = int(os.getenv("DB_POOL_RECYCLE", 3600))
                self.pool_timeout: int = int(os.getenv("DB_POOL_TIMEOUT", 30))

            @property
            def sync_url(self)->str:
                encoded_password = urllib.parse.quote_plus(self.password)
                return f"mysql+pymysql://{self.user}:{encoded_password}@{self.host}:{self.port}/{self.db_name}?charset={self.charset}"

            @property
            def async_url(self)->str:
                encoded_password = urllib.parse.quote_plus(self.password)
                return f"mysql+aiomysql://{self.user}:{encoded_password}@{self.host}:{self.port}/{self.db_name}?charset={self.charset}"


            def get_options(self,async_pool: bool = False):
                """
                数据库配置
                :return:
                """

                # 连接池配置
                pool_options = {
                    "pool_size": self.pool_size,
                    "max_overflow": self.max_overflow,
                    "pool_recycle": self.pool_recycle,
                    "pool_timeout": self.pool_timeout,
                    "pool_pre_ping": True,
                    "echo": self.debug,
                }
                # 时区配置
                connect_args: dict[str, Any] = {}
                if self.use_tz:
                    connect_args["init_command"] = f"SET time_zone='{self.timezone}'"

                return pool_options, connect_args

        return DatabaseConfig()


# 实例化
conf = Config()
